package com.lechi.web.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.lechi.iot.android.channel.IIotTcpChannel;
import com.lechi.iot.android.entity.OutDeviceCmd;
import com.lechi.iot.netty.utils.NettyCacheUtils;
import com.lechi.web.common.annotation.DataScope;
import com.lechi.web.common.enums.ErrorCodeEnum;
import com.lechi.web.common.exception.ServiceException;
import com.lechi.web.framework.log.IotExceptionLog;
import com.lechi.web.framework.util.GuavaCacheUtil;
import com.lechi.web.service.IIotDeviceService;
import com.lechi.web.system.domain.IotDeviceBo;
import com.lechi.web.system.mapper.iot.IotDeviceMapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

/**
 * 设备Service业务层处理
 *
 * @author yangguang
 */
@Slf4j
@Service("IotDeviceService")
@RequiredArgsConstructor
public class IotDeviceServiceImpl implements IIotDeviceService {

    private final IotDeviceMapper iotDeviceMapper;

    /**
     * 查询设备
     *
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public IotDeviceBo selectIotDeviceById(Long id) {
        try {
            return iotDeviceMapper.selectIotDeviceById(id);
        } catch (Exception e) {
            StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[1];
            String method = Thread.currentThread().getName() + ":" + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName();
            CompletableFuture.runAsync(IotExceptionLog.exceptionLog(e, "通过设备ID查询设备", method, id));
            throw new ServiceException(ErrorCodeEnum.QUERY_ERROR.getValue(), ErrorCodeEnum.QUERY_ERROR.getKey());
        }
    }

    /**
     * 查询设备列表
     *
     * @param iotDeviceBo 设备
     * @return 设备
     */

    @Override
    @DataScope(deviceAlias = "d")
    public List<IotDeviceBo> selectIotDeviceList(IotDeviceBo iotDeviceBo) {
        try {
            return iotDeviceMapper.selectIotDeviceList(iotDeviceBo);
        } catch (Exception e) {
            StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[1];
            String method = Thread.currentThread().getName() + ":" + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName();
            CompletableFuture.runAsync(IotExceptionLog.exceptionLog(e, "查询设备列表", method, iotDeviceBo));
            throw new ServiceException(ErrorCodeEnum.QUERY_ERROR.getValue(), ErrorCodeEnum.QUERY_ERROR.getKey());
        }
    }


    /**
     * 根据角色id查询设备台账列表
     *
     * @param roleId 设备
     * @return 设备
     */

    @Override
//    @DataScope(deviceAlias = "d")
    public List<Long> selectDeviceListByRoleId(Long roleId) {
        try {
            return iotDeviceMapper.selectDeviceListByRoleId(roleId);
        } catch (Exception e) {
            StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[1];
            String method = Thread.currentThread().getName() + ":" + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName();
            CompletableFuture.runAsync(IotExceptionLog.exceptionLog(e, "根据角色id查询设备台账列表", method, roleId));
            throw new ServiceException(ErrorCodeEnum.QUERY_ERROR.getValue(), ErrorCodeEnum.QUERY_ERROR.getKey());
        }
    }

    /**
     * 新增设备
     *
     * @param iotDeviceBo 设备
     */
    @Override
    public void insertIotDevice(IotDeviceBo iotDeviceBo) {
        iotDeviceBo.setCreateTime(new Date());
        try {
            iotDeviceMapper.insertIotDevice(iotDeviceBo);
        } catch (Exception e) {
            StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[1];
            String method = Thread.currentThread().getName() + ":" + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName();
            CompletableFuture.runAsync(IotExceptionLog.exceptionLog(e, "新增设备", method, iotDeviceBo));
            throw new ServiceException(ErrorCodeEnum.ADD_ERROR.getValue(), ErrorCodeEnum.ADD_ERROR.getKey());
        }
    }

    /**
     * 修改设备
     *
     * @param iotDeviceBo 设备
     */
    @Override
    public void updateIotDevice(IotDeviceBo iotDeviceBo) {
        try {
            iotDeviceMapper.updateIotDevice(iotDeviceBo);
        } catch (Exception e) {
            StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[1];
            String method = Thread.currentThread().getName() + ":" + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName();
            CompletableFuture.runAsync(IotExceptionLog.exceptionLog(e, "修改设备", method, iotDeviceBo));
            throw new ServiceException(ErrorCodeEnum.EDIT_ERROR.getValue(), ErrorCodeEnum.EDIT_ERROR.getKey());
        }
    }

    /**
     * 批量删除设备
     *
     * @param ids 需要删除的设备主键
     */
    @Override
    public void deleteIotDeviceByIds(Long[] ids) {
        try {
            iotDeviceMapper.deleteIotDeviceByIds(ids);
        } catch (Exception e) {
            StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[1];
            String method = Thread.currentThread().getName() + ":" + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName();
            CompletableFuture.runAsync(IotExceptionLog.exceptionLog(e, "通过设备主键批量删除设备", method, ids));
            throw new ServiceException(ErrorCodeEnum.DELETE_ERROR.getValue(), ErrorCodeEnum.DELETE_ERROR.getKey());
        }
    }

    @Override
    public void sendCmdToApp(String androidDeviceSN, OutDeviceCmd outDeviceCmd) {
        String hostName = GuavaCacheUtil.getBiDeviceSnAndIPMap().get(androidDeviceSN);
        if (Objects.isNull(hostName) || Objects.equals(androidDeviceSN, hostName)) {
            log.error("升级指令：{} 暂停发送, 设备序列号:{} 没有注册~！", "volume", androidDeviceSN);
            throw new ServiceException(ErrorCodeEnum.SEND_ERROR.getValue(), ErrorCodeEnum.SEND_ERROR.getKey());
        }
        IIotTcpChannel iotTcpChannel = NettyCacheUtils.get(hostName, IIotTcpChannel.class);
        if (iotTcpChannel == null) {
            log.error("升级指令发送失败，设备IP：{}, 设备序列号:{} 获取tcpChannel值为空， 请联系工程师解决！", hostName, androidDeviceSN);
            throw new ServiceException(ErrorCodeEnum.SEND_ERROR.getValue(), ErrorCodeEnum.SEND_ERROR.getKey());
        }
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
        log.info("待下发设备序列号：{}，设备IP：{}， 指令数据：{}", androidDeviceSN, hostName, outDeviceCmd.getCmd());
        byteBuf.writeCharSequence(JSONObject.toJSONString(outDeviceCmd), Charset.defaultCharset());
        iotTcpChannel.send(byteBuf);
    }

}
